
<?php

/**
 * This is the model class for table "temper_ext_releves".
 *
 * The followings are the available columns in table 'temper_ext_releves':
 * @property string $dte
 * @property string $temperature
 */
class TemperExtReleve extends CActiveRecord {
    /*
     * N° de série du capteur de température 1-Wire
     */

    public $W1Serial = '28-0000045d28e0';
    // Champs calculés
    public $dteGroup = null;
    public $tmoy = null;
    public $tmin = null;
    public $tmax = null;
    public $tnb = null;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return TemperExtReleve the static model class
     */
    public static function model($className = __CLASS__) {
	  return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
	  return 'mesures_temperext_releves';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
	  // NOTE: you should only define rules for those attributes that
	  // will receive user inputs.
	  return array(
		array('dte, temperature', 'safe'),
		// The following rule is used by search().
		// Please remove those attributes that should not be searched.
		array('dte, temperature', 'safe', 'on' => 'search'),
	  );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
	  // NOTE: you may need to adjust the relation name and the related
	  // class name for the relations automatically generated below.
	  return array(
	  );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	  return array(
		'dte' => 'Date et heure du relevé',
		'temperature' => 'Température',
	  );
    }

    /*
     * Lecture de la température à partir de la sonde
     * avec vérification de la valeur lue
     */

    public function getTemperature() {

	  // Activation des modules 1-wire
	  passthru('modprobe w1-gpio');
	  passthru('modprobe w1-therm');

	  $content = file_get_contents('/sys/bus/w1/devices/' . $this->W1Serial . '/w1_slave');
	  $content = split('t=', $content);

	  $this->temperature = round($content[1] / 1000, 1);
	  $this->dte = date('Y-m-d H:i');

	  $err = '';

	  // Temperature non numérique => erreur
	  if (!is_numeric($this->temperature)) {
		Yii::log('Donnée non numérique (t° = ' . $this->temperature . ')', 'warning', 'mesures.TemperExt');
		return false;
	  }

	  // Température numérique
	  else {

		$avgCriteria = new CDbCriteria();
		$avgCriteria->select = 'AVG(temperature) AS tmoy ';
		$avgCriteria->condition = "dte >= NOW() - INTERVAL 30 MINUTE";

		$moyResult = $this->findAll($avgCriteria);
		$moy = $moyResult[0]->tmoy;


		// Si on a une moyenne (pas de vérif si 1er enregistrement)
		// On vérifie que la mesure n'a pas plus de 3° d'écart
		if (!is_null($moy)) {
		    $ecart = abs($this->temperature - $moy);
		    if ($ecart > 3) {

			  Yii::log('Données invalides (t° = ' . $this->temperature . ' / moy = ' . $moy . ')', 'warning', 'mesures.TemperExt');
			  return false;
		    }
		}
	  }

	  // Pas d'erreur détectée
	  return true;
    }

    public static function getGraphHeure() {
	  $graphOptions = array(
		'title' => array('text' => 'Températures par heure'),
		'xAxis' => array('tickInterval' => 3600*1000),
	  );

	  $graphData = TemperExtReleve::getGraphData(array('groupby' => "CONCAT(SUBSTR(dte, 1,13), ':00')", 'duree' => '7 DAY'));
	  return CMap::mergeArray($graphOptions, $graphData);
    }

    /*
     * Récupération des données de température les graphs
     * @options array : liste des paramètres (groupby, duree)
     * @return array
     */

    private static function getGraphData($options = array()) {
	  $criteria = new CDbCriteria();
	  $criteria->select = $options['groupby'] . ' AS dteGroup, AVG(temperature) AS tmoy ';
	  $criteria->condition = "dte >= NOW() - INTERVAL " . $options['duree'];
	  $criteria->group = 'dteGroup';
	  $criteria->order = 'dteGroup';

	  $result = TemperExtReleve::model()->findAll($criteria);

	  $avg = array();

	  foreach ($result as $rs) {

		$dte = 1000 * strtotime($rs->dteGroup);
		$dte = (string) $dte;

		$avg[] = array((float) $dte, round($rs->tmoy, 1));
	  }

	  $graph = array(
		'yAxis' => array(
		    'title' => array('text' => '°C'),
		),
		'xAxis' => array('type' => 'datetime'),
		'series' => array(
		    array(
			  'name' => 'Température',
			  'data' => $avg,
			  'zIndex' => 1,
			  'color' => '#c0392b',
			  'marker' => array(
				'enabled' => false,
			  ),
		    ),
		),
	  );
	  return $graph;
    }

}